<?php

namespace App\Http\Controllers\CallingCards\RMS;

use App\Http\Controllers\BaseController;
use App\Http\Middleware\CallingCards\RmsAuth;
use App\Http\Validate\CallingCards\Article\HomeArticleValidate;
use App\Models\FeishuCallingCard\FeishuCallingCardsArticle;
use App\Models\FeishuCallingCard\FeishuCallingCardUsersStoriesLog;
use App\Service\CallingCards\Article\HomeArticleService;
use App\Service\CallingCards\Article\WechatArticleService;
use App\Service\CallingCards\UsersStoriesLogService;
use App\Service\OpenShop\User\RmsUserService;
use Exception;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
use Illuminate\Validation\ValidationException;
use Kuafu\File\FileUtil;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
use Psr\SimpleCache\InvalidArgumentException;

/**
 * RMS后台埋的坑，0代表启用，1代表禁用
 */
class FranchiseeController extends BaseController
{
    public function articles(Request $request)
    {
        $pageNum  = (int)$request->get('pageNum', 1);
        $pageSize = (int)$request->get('pageSize', 20);

        $type     = (int)$request->type;
        $articles = FeishuCallingCardsArticle::query()
            ->when($type, function ($query) use ($type) {
                $query->where('type', $type);
            })
            ->orderBy('weight', 'desc')
            ->orderBy('id', 'desc')
            ->paginate($pageSize, ['*'], 'pageNum', $pageNum);
        return $this->success([
            'list'     => $articles->map(function (FeishuCallingCardsArticle $article) {
                $arr = $article->toArray();
                if (strlen($arr['originalImage'])) {
                    $arr['originalImage'] = FileUtil::domain() . '/' . ltrim($arr['originalImage'], '/');
                }
                if (strlen($arr['thumbImage'])) {
                    $arr['thumbImage'] = FileUtil::domain() . '/' . ltrim($arr['thumbImage'], '/');
                }
                $arr['createdAt'] = $article->createdAt->toDateTimeString();
                $arr['updatedAt'] = $article->updatedAt->toDateTimeString();
                $arr['status']    = 1 - $article->status;
                $arr["typeText"]  = FeishuCallingCardsArticle::ARTICLE_TYPE_MAP[$article->type] ?? "-";
                return $arr;
            }),
            'pageNum'  => $pageNum,
            'pageSize' => $pageSize,
            'count'    => $articles->total(),
        ]);
    }

    public function saveArticle(Request $request)
    {
        $id       = (int)$request->id;
        $this->validate($request, [
            'type'       => 'required|int|' . Rule::in(array_keys(FeishuCallingCardsArticle::ARTICLE_FROM_TEXT[FeishuCallingCardsArticle::ARTICLE_FROM_1])),
            'name'       => 'string|max:64',
            'thumbImage' => 'string',
            'weight'     => 'int',
            'status'     => 'int|in:0,1',
        ]);
        $type      = (int)$request->get('type', 0);
        $wechatUrl = (string)$request->get('wechatUrl', '');

        $extra = [];
        if (strlen($request->extra)) {
            $extra = json_decode($request->extra, true);
            if (!is_array($extra)) {
                return $this->fail(422, 'extra参数不是json');
            }
        }
        if ($id) {
            $article = FeishuCallingCardsArticle::find($id);
            if (null === $article) {
                return $this->fail(404, 'ID不存在，刷新后再试');
            }
        } else {
            if ($type == FeishuCallingCardsArticle::ARTICLE_TYPE_40) {// 企微文章 创建文章
                if (!preg_match('/^https?:\\/\\/mp\\.weixin\\.qq\\.com/', $wechatUrl)) {
                    return $this->fail(400, '链接请以https://mp.weixin.qq.com开头');
                }
                (new WechatArticleService)->wechatArticleSave($wechatUrl, RmsAuth::$userId);
                return $this->success();
            }
            $article = new FeishuCallingCardsArticle;
        }
        $article->fill($request->all());
        if ($type != FeishuCallingCardsArticle::ARTICLE_TYPE_40) {// 企微文章 创建文章
            $article->extra = $extra;
        }
        $article->content       = (string)$request->post('content', '');
        $article->status        = 1 - $request->status;
        $article->thumbImage    = ltrim(parse_url((string)$request->thumbImage)['path'], '/');
        $article->originalImage = ltrim(parse_url((string)$request->originalImage)['path'], '/');
        if (!$article->createdByUid) {
            $article->createdByUid = RmsAuth::$userId;
        }
        $article->updatedByUid = RmsAuth::$userId;
        $article->save();
        return $this->success();
    }

    /**
     * @throws InvalidArgumentException
     * @throws ValidationException
     */
    public function articleStatus(Request $request): JsonResponse
    {
        $this->validate($request, [
            'id'     => 'required|int',
            'status' => 'required|int|in:0,1',
        ]);
        FeishuCallingCardsArticle::query()
                                 ->where('id', $request->id)
                                 ->update([
                                     'status' => 1 - $request->status,
                                 ]);

        HomeArticleService::removeHomeCache();
        return $this->success();
    }

    /**
     * @return JsonResponse
     * @throws Exception
     */
    public function homeArticleForm(): JsonResponse
    {
        return $this->success(HomeArticleService::getFormDetail());
    }

    /**
     * 添加文章
     *
     * @param Request $request
     * @return JsonResponse
     * @throws ValidationException
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     * @throws Exception
     */
    public function homeArticleAdd(Request $request): JsonResponse
    {
        $requestParams = HomeArticleValidate::homeArticleAddValidate($request->all());
        HomeArticleService::homeArticleAdd($requestParams);
        return $this->success();
    }

    /**
     * @param Request $request
     * @param int $id
     * @return JsonResponse
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     * @throws ValidationException
     * @throws Exception
     */
    public function homeArticleEditForm(Request $request, int $id): JsonResponse
    {
        HomeArticleValidate::homeArticleEditFormValidate($request->merge(["id" => $id])->all());
        return $this->success(HomeArticleService::homeArticleEditForm($id));
    }

    /**
     * 编辑文章
     *
     * @param Request $request
     * @param int $id
     * @return JsonResponse
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     * @throws ValidationException
     * @throws Exception
     */
    public function homeArticleEdit(Request $request, int $id): JsonResponse
    {
        $requestParams = HomeArticleValidate::homeArticleEditValidate($request->merge(["id" => $id])->all());
        HomeArticleService::homeArticleEdit($requestParams);
        return $this->success();
    }

    /**
     * 微信服务号文章信息
     * @param Request $request
     * @param int $id
     * @return JsonResponse
     */
    public function getArticleInfo(Request $request, int $id): JsonResponse
    {
        return $this->success((new WechatArticleService)->getArticleInfo($id));
    }

    /**
     * 文章阅读事件
     * @param Request $request
     * @return JsonResponse
     * @throws ValidationException
     */
    public function article(Request $request): JsonResponse
    {
        $this->validate(
            $request, [
                'articlesId' => 'required|integer',
                'type'       => 'required|integer|' . Rule::in(array_keys(FeishuCallingCardUsersStoriesLog::TYPE_TEXT_MAPPING)),
            ]
        );
        $data['storiesId']       = (int)$request->get('articlesId', 0);      // 文章id
        $data['isReadCompleted'] = (int)$request->get('isReadCompleted', 0); // 是否完成阅读
        $data['isClickJoin']     = (int)$request->get('isClickJoin', 0);     // 是否点击加盟
        $data['type']            = (int)$request->get('type', 0);            // 类型 1-进入文章 2-心跳更新数据 3-主动关闭完成阅读

        $unionid = $request->unionid ?? '';

        return $this->success(UsersStoriesLogService::article(null, $data, FeishuCallingCardUsersStoriesLog::SOURCE_WECHAT_OFFICIAL, $unionid));
    }
}
